<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TIMEOUT HANDLER</title>
    <style>
        #result { 
            width: 200px;
            height: 100px;
            border: solid 1px #90b
        }
        .error{
            color: #e60f0f;
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
</body>
<script lang="javascript">
    const BASE_URL = "http://localhost:8000"
    // get button element
    const btn = document.getElementsByTagName("button")[0];
    const result = document.getElementById("result");
    // bind action to element
    btn.addEventListener("click", () => {
        const xhr = new XMLHttpRequest();
        // timeout setting
        xhr.timeout = 2000;
        xhr.ontimeout = function(){
            result.innerHTML = "network error, please try again later";
            result.setAttribute("class", "error");
        }
        xhr.onerror = function(){
            result.innerHTML = "network error, please try again later ERROR!";
            result.setAttribute("class", "error");
        }
        xhr.open('get', BASE_URL + '/timeout', true);
        xhr.send()
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status < 300){
                    result.innerHTML = xhr.response;
                }else{}
            }
        }
    })
</script>

</html>